//
//  MainTabView.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI

struct MainTabView: View {
    @State private var selectedTab = 0
    @StateObject private var apiService = APIService.shared
    @State private var bottomNavItems: [BottomNavigationItem] = []
    @State private var isLoading = true
    
    var body: some View {
        if isLoading {
            // 显示加载状态
            ProgressView("加载中...")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .onAppear {
                    loadBottomNavigation()
                }
        } else {
            VStack(spacing: 0) {
                // 主内容区域
                getViewForTab(index: selectedTab, item: bottomNavItems[selectedTab])
                
                // 自定义底部导航栏
                HStack(spacing: 0) {
                    ForEach(Array(bottomNavItems.enumerated()), id: \.offset) { index, item in
                        Button(action: {
                            selectedTab = index
                        }) {
                            VStack(spacing: 4) {
                                AsyncImage(url: URL(string: selectedTab == index ? item.checkedImageURL : item.uncheckedImageURL)) { image in
                                    image
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .frame(width: 20, height: 20)
                                } placeholder: {
                                    // 使用默认图标作为占位符
                                    Image(getDefaultIcon(for: index, selected: selectedTab == index))
                                        .renderingMode(.template)
                                        .resizable()
                                        .aspectRatio(contentMode: .fit)
                                        .frame(width: 20, height: 20)
                                        .foregroundColor(selectedTab == index ? ThemeHelper.shared.getColor() : Color(red: 51/255, green: 51/255, blue: 51/255))
                                }
                                
                                Text(item.name)
                                     .font(.system(size: 10))
                                     .foregroundColor(selectedTab == index ? ThemeHelper.shared.getColor() : Color(red: 51/255, green: 51/255, blue: 51/255))
                            }
                        }
                        .frame(maxWidth: .infinity)
                    }
                }
                .padding(.vertical, 8)
                .background(Color(.systemBackground))
                .shadow(color: .black.opacity(0.1), radius: 1, x: 0, y: -1)
            }
        }
    }
    
    // 根据索引返回对应的视图
    @ViewBuilder
    private func getViewForTab(index: Int, item: BottomNavigationItem) -> some View {
        switch index {
        case 0:
            HomeView()
        case 1:
            CategoryView()
        case 2:
            DiscoverView()
        case 3:
            CartView()
        case 4:
            UserView()
        default:
            Text("未知页面")
        }
    }
    
    // 获取默认图标（作为网络图片的备用）
    private func getDefaultIcon(for index: Int, selected: Bool) -> String {
        switch index {
        case 0:
            return selected ? "shouxuan" : "shouwei"
    	    case 1:
            return selected ? "fenxuan" : "fenwei"
        case 2:
            return selected ? "tab3" : "tab3wei"
        case 3:
            return selected ? "gouxuan" : "gouwei"
        case 4:
            return selected ? "woxuan" : "wowei"
        default:
            return "shouwei"
        }
    }
    
    private func loadBottomNavigation() {
        Task {
            do {
                let response = try await apiService.fetchBottomNavigation()
                await MainActor.run {
                    self.bottomNavItems = response.data?.bottomNavigationList ?? []
                    self.isLoading = false
                }
            } catch {
                print("加载底部导航失败: \(error)")
                // 使用默认配置
                await MainActor.run {
                    self.bottomNavItems = getDefaultBottomNavItems()
                    self.isLoading = false
                }
            }
        }
    }
    
    // 默认底部导航配置（API失败时使用）
    private func getDefaultBottomNavItems() -> [BottomNavigationItem] {
        return [
            BottomNavigationItem(id: 1, name: "首页", link: "", unchecked: "", checked: ""),
            BottomNavigationItem(id: 2, name: "分类", link: "", unchecked: "", checked: ""),
            BottomNavigationItem(id: 3, name: "逛逛", link: "", unchecked: "", checked: ""),
            BottomNavigationItem(id: 4, name: "购物车", link: "", unchecked: "", checked: ""),
            BottomNavigationItem(id: 5, name: "我的", link: "", unchecked: "", checked: "")
        ]
    }
}

struct MainTabView_Previews: PreviewProvider {
    static var previews: some View {
        MainTabView()
    }
}
